package br.com.sovi.gwt.server.service.rastreamento;

import java.util.ArrayList;
import java.util.List;

import br.com.sovi.gwt.client.entity.Ponto;
import br.com.sovi.gwt.client.entity.rastreamento.Rastreado;
import br.com.sovi.gwt.client.entity.rastreamento.Rastreavel;
import br.com.sovi.gwt.client.rastreamento.service.RastreamentoService;
import br.com.sovi.gwt.server.Constants;
import br.com.sovi.gwt.server.json.entity.DispositivoVO;
import br.com.sovi.gwt.server.json.entity.PontoVO;
import br.com.sovi.gwt.server.rest.RestController;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.sun.jersey.api.client.GenericType;

@SuppressWarnings("serial")
public class RastreamentoServiceImpl extends RemoteServiceServlet implements RastreamentoService {

	@Override
	public List<Rastreado> getAllDispositivos() {
		try {
			List<DispositivoVO> vos = getSerialDispositivos();
			int length = vos.size();

			List<Rastreado> list = new ArrayList<Rastreado>(length);

			for (int i = 0; i < length; i++) {
				DispositivoVO vo = vos.get(i);
				Ponto ponto = findUltimoPoint(vo.getSerial());
				list.add(new Rastreado(vo.getNome(), vo.getSerial(), ponto));
			}

			return list;
		}
		catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	private List<DispositivoVO> getSerialDispositivos() {
		String url = Constants.BASE_URL + "/dispositivo/allByEmpresa";
		return (List<DispositivoVO>) RestController.get(url, new GenericType<List<DispositivoVO>>() {
		});
	}

	private Ponto findUltimoPoint(String serial) {
		String url = Constants.BASE_URL + "/ponto/ultimoFromDispositivo?dispositivo=" + serial;
		PontoVO ponto = (PontoVO) RestController.get(url, new GenericType<PontoVO>() {
		});

		return ponto.toPonto();
	}

	@Override
	public Ponto getUltimoPonto(Rastreavel rastreavel) {
		return findUltimoPoint(rastreavel.getSerial());
	}

}
